using MediatR;
using UniversalAdmin.Application.Common;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Domain.Interfaces;

namespace UniversalAdmin.Application.Features.Roles.Queries.GetRolesByName;

public class GetRolesByNameQueryHandler : IRequestHandler<GetRolesByNameQuery, ApiResult<PagedResult<RoleDto>>>
{
  private readonly IUnitOfWork _unitOfWork;

  public GetRolesByNameQueryHandler(IUnitOfWork unitOfWork)
  {
    _unitOfWork = unitOfWork;
  }

  public async Task<ApiResult<PagedResult<RoleDto>>> Handle(GetRolesByNameQuery request, CancellationToken cancellationToken)
  {
    var (items, totalCount) = await _unitOfWork.RoleRepository.GetPagedRolesAsync(
        keyword: request.Name,
        pageIndex: request.PageIndex,
        pageSize: request.PageSize
    );

    var dtos = items.Select(r => new RoleDto
    {
      Id = r.Id,
      Name = r.Name,
      Description = r.Description
    }).ToList();

    var result = new PagedResult<RoleDto>
    {
      Items = dtos,
      TotalCount = totalCount,
      PageIndex = request.PageIndex,
      PageSize = request.PageSize
    };

    return ApiResult<PagedResult<RoleDto>>.Success(result, "查询成功");
  }
}